package com.tool.jedis;

import cn.hutool.core.util.ObjectUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

public class FactoryJedis {

    private static final Map<String, JedisPool> jedisPoolMap = new HashMap<>();

    static {
        JedisPoolConfig jedisPoolConfig = getJedisPoolConfig();

        // 初始化连接池类（使用自定义连接池参数）
        jedisPoolMap.put("115.29.192.252", new JedisPool(jedisPoolConfig, "115.29.192.252", 6379, null, "zzfmhb"));
        jedisPoolMap.put("61.52.247.249", new JedisPool(jedisPoolConfig, "61.52.247.249", 20001, null, "zzfmhb"));
    }

    public static Jedis jedis(String key) {
        JedisPool jedisPool = getJedisPool(key);
        if (ObjectUtil.isNull(jedisPool)) {
            return null;
        }
        return jedisPool.getResource();
    }

    public static Jedis jedis() {
        Jedis jedis = jedis("61.52.247.249");
        return jedis;
    }

    public static Jedis get(String host, Integer port, String pass) {
        return getJedisPool(host, port, pass).getResource();
    }

    /**
     * 获取并初始化jedis-pool
     * @param host
     * @param port
     * @param pass
     * @return
     */
    public static JedisPool getJedisPool(String host, Integer port, String pass) {
        JedisPool jedisPool = jedisPoolMap.get(host);
        if (ObjectUtil.isNull(jedisPool)) {
            jedisPool = new JedisPool(getJedisPoolConfig(), host, port, null, pass);
            jedisPoolMap.put(host, jedisPool);
        }
        return jedisPool;
    }

    public static JedisPool getJedisPool(String host) {
        return jedisPoolMap.get(host);
    }

    private static JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 设置连接池的最大连接数
        jedisPoolConfig.setMaxTotal(10);
        // 设置连接池允许的最大空闲连接数
        jedisPoolConfig.setMaxIdle(8);
        return jedisPoolConfig;
    }
}
